package com.zyj.check.service.impl;

import com.zyj.check.domain.AssetsCheckDetail;
import com.zyj.check.service.IExcelImage;
import com.zyj.common.config.ZyjConfig;
import com.zyj.common.core.domain.AjaxResult;
import com.zyj.common.exception.UtilException;
import com.zyj.common.utils.DateUtils;
import com.zyj.common.utils.StringUtils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.List;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;

import com.zyj.system.service.ISysDictDataService;
import com.zyj.system.service.ISysDictTypeService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by zyjaz on 2022/5/26.
 */
@Service
public class ExcelImage implements IExcelImage{

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private ISysDictDataService dictDataService;



    public AjaxResult creatExportCheckReport(Map info,List list,String title, String sheetName,String assetsTypeimg,String checkinfoimg) {

        if(null != list && list.size()>0){
            HSSFWorkbook workbook = new HSSFWorkbook(); // 创建一个excel对象

            HSSFSheet sheet = workbook.createSheet(title); // 创建表格
            //画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
            // 写入sheet数据
            try {
                writeSheet(workbook, sheet, info,list, patriarch,assetsTypeimg,checkinfoimg);
            } catch (IOException e) {
                e.printStackTrace();
            }
            OutputStream out = null;
            try
            {
                String filename = encodingFilename(sheetName);
                out = new FileOutputStream(getAbsoluteFile(filename));
                workbook.write(out);
                return AjaxResult.success(filename);
            }
            catch (Exception e)
            {
                throw new UtilException("导出Excel失败，请联系网站管理员！");
            }
            finally
            {
                IOUtils.closeQuietly(workbook);
                IOUtils.closeQuietly(out);
            }
        }else{
            throw new UtilException("导出Excel失败，请联系网站管理员！");
        }
    }

    /*
     * 得到单元格内容
     */
    public static HSSFCell getCell(HSSFRow row, int colIndex){
        HSSFCell cell = row.getCell(colIndex);
        if (cell == null) {
            cell = row.createCell(colIndex);
            cell.setCellValue("");
        }
        return cell;
    }
    /*
     * 导出Excel
     */
    public void exportExcel(String path, String fileName, HSSFWorkbook wb){
        OutputStream os = null;
        try {
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(path + File.separator + fileName);
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if (os != null)
                    os.close();
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 写入sheet数据
     * @param workbook
     * @param sheet
     * @param list
     * @throws IOException
     */
    public void writeSheet(HSSFWorkbook workbook, HSSFSheet sheet,Map info,List list, HSSFPatriarch patriarch,String assetsTypeimg,String checkinfoimg) throws IOException{
        int rowIndex = 0;
        HSSFRow row = null;//行
        HSSFCell cell = null;//列
        ByteArrayOutputStream byteArrayOut = null;//字符输出对象
        String baseArr[];//存放格式化base64Str后的数组 0-图片格式；1-base64字符
        String type;//图片格式
        BufferedImage buffer_Img;
        HSSFClientAnchor anchor;
        if (row == null) row = sheet.createRow(rowIndex);
        if(info!=null && !info.isEmpty()){
            String title = (String)info.get("title");
            HSSFRichTextString titleStr = new HSSFRichTextString("《"+title+"》的盘点报告"); //textValue是要设置大小的单元格数据
            HSSFFont font = workbook.createFont();
            font.setBold(true);
            font.setFontHeightInPoints((short) 20);//设置excel数据字体大小
            titleStr.applyFont(font);
            cell = getCell(row, 2);
            cell.setCellValue(titleStr);

            String exporttime = (String)info.get("exporttime");
            cell = getCell(sheet.createRow(rowIndex+1), 3);
            cell.setCellValue("报告时间："+exporttime);

            HSSFRichTextString checkNoStr = new HSSFRichTextString("盘点编号:"); //textValue是要设置大小的单元格数据
            HSSFFont checkNofont = workbook.createFont();
            checkNofont.setBold(true);
            checkNofont.setFontHeightInPoints((short) 10);//设置excel数据字体大小
            checkNoStr.applyFont(checkNofont);
            row = sheet.createRow(rowIndex+2);
            cell = getCell(row, 0);
            cell.setCellValue(checkNoStr);
            String checkNo = (String)info.get("checkNo");
            cell = getCell(row, 1);
            cell.setCellValue(checkNo);

            HSSFRichTextString checkTimeStr = new HSSFRichTextString("盘点时间:"); //textValue是要设置大小的单元格数据
            HSSFFont checkTimefont = workbook.createFont();
            checkTimefont.setBold(true);
            checkTimefont.setFontHeightInPoints((short) 10);//设置excel数据字体大小
            checkTimeStr.applyFont(checkTimefont);
            row = sheet.createRow(rowIndex+3);
            cell = getCell(row, 0);
            cell.setCellValue(checkTimeStr);
            String checkTime = DateUtils.dateTime((Date)info.get("checkTime"));
            cell = getCell(row, 1);
            cell.setCellValue(checkTime);

            HSSFRichTextString assetsTypeStr = new HSSFRichTextString("资产类别:"); //textValue是要设置大小的单元格数据
            HSSFFont assetsTypefont = workbook.createFont();
            assetsTypefont.setBold(true);
            assetsTypefont.setFontHeightInPoints((short) 10);//设置excel数据字体大小
            assetsTypeStr.applyFont(assetsTypefont);
            row = sheet.createRow(rowIndex+4);
            cell = getCell(row, 0);
            cell.setCellValue(assetsTypeStr);
            String assetsType = (String)info.get("assetsType");
            cell = getCell(row, 1);
            cell.setCellValue(assetsType);

            HSSFRichTextString assetsStatusStr = new HSSFRichTextString("资产状态:"); //textValue是要设置大小的单元格数据
            HSSFFont assetsStatusfont = workbook.createFont();
            assetsStatusfont.setBold(true);
            assetsStatusfont.setFontHeightInPoints((short) 10);//设置excel数据字体大小
            assetsStatusStr.applyFont(assetsStatusfont);
            row = sheet.createRow(rowIndex +5);
            cell = getCell(row, 0);
            cell.setCellValue(assetsStatusStr);
            String assetsStatus = (String)info.get("assetsStatus");
            cell = getCell(row, 1);
            cell.setCellValue(assetsStatus);

            HSSFRichTextString detpNameStr = new HSSFRichTextString("盘点部门:"); //textValue是要设置大小的单元格数据
            HSSFFont detpNamefont = workbook.createFont();
            detpNamefont.setBold(true);
            detpNamefont.setFontHeightInPoints((short) 10);//设置excel数据字体大小
            detpNameStr.applyFont(detpNamefont);
            row = sheet.createRow(rowIndex +6);
            cell = getCell(row, 0);
            cell.setCellValue(detpNameStr);
            String detpName = (String)info.get("detpName");
            cell = getCell(row, 1);
            cell.setCellValue(detpName);

        }

        // 盘点概况图片
        if (StringUtils.isNotBlank(checkinfoimg)) {
            byteArrayOut = new ByteArrayOutputStream();
            // 格式化，取得图片类型和base64字符串码
            baseArr = base64SplitTypeAndStr(checkinfoimg);
            type = baseArr[0];
            // base64转BufferedImage
            buffer_Img = base64ToBufferedImage(baseArr[1]);
            ImageIO.write(buffer_Img, type, byteArrayOut);// 写入
            //图片位置
            anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 10, (short) 3, 20);
            // 插入图片
            patriarch.createPicture((HSSFClientAnchor) anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

        }
        // 资产盘点分类统计图片
        if (StringUtils.isNotBlank(assetsTypeimg)) {
//                row.setHeight((short)2400);// 设置行高
            byteArrayOut = new ByteArrayOutputStream();
            // 格式化，取得图片类型和base64字符串码
            baseArr = base64SplitTypeAndStr(assetsTypeimg);
            type = baseArr[0];
            // base64转BufferedImage
            buffer_Img = base64ToBufferedImage(baseArr[1]);
            ImageIO.write(buffer_Img, type, byteArrayOut);// 写入
            //图片位置
            anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 10, (short) 10, 20);
            // 插入图片
            patriarch.createPicture((HSSFClientAnchor) anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
        }

        if(list!=null && !list.isEmpty()){
            HSSFRow row1 = null;//行
            HSSFCell cell1 = null;//列
            HSSFSheet sheet2 = workbook.createSheet("盘点明细"); // 创建表格
            if (row1 == null) row1 = sheet2.createRow(0);
//            row1.setHeight((short)(30*20));
//            row1.setHeightInPoints((short)30);
            sheet2.setColumnWidth(0,45*100);
            HSSFCellStyle cellStyle = exportExcelSetCellStyle(workbook);
            cell1= getCell(row1, 0);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("资产编号");

            sheet2.setColumnWidth(1, 30*100);
            cell1= getCell(row1, 1);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("是否盘点");

            sheet2.setColumnWidth(2, 50*100);
            cell1= getCell(row1, 2);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("资产名称");

            sheet2.setColumnWidth(3, 50*100);
            cell1= getCell(row1, 3);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("SN号");

            sheet2.setColumnWidth(4, 30*100);
            cell1= getCell(row1, 4);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("资产状态");

            sheet2.setColumnWidth(5, 50*100);
            cell1= getCell(row1, 5);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("资产类别");

            sheet2.setColumnWidth(6, 50*100);
            cell1= getCell(row1, 6);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("资产规格");

            sheet2.setColumnWidth(7, 40*100);
            cell1= getCell(row1, 7);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("所在部门");

            sheet2.setColumnWidth(8, 30*100);
            cell1= getCell(row1, 8);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("使用人名称");

            sheet2.setColumnWidth(9, 30*100);
            cell1= getCell(row1, 9);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("盘点人");

            sheet2.setColumnWidth(10, 40*100);
            cell1= getCell(row1, 10);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue("盘点时间");


            for(int i=1;i<=list.size();i++){
                row1 = sheet2.createRow(i);
                AssetsCheckDetail ad = (AssetsCheckDetail)list.get(i-1);

                cell1= getCell(row1, 0);
                cell1.setCellValue(ad.getAssetsId());

                cell1= getCell(row1, 1);
                cell1.setCellValue(dictDataService.selectDictLabel("check_flag", ad.getCheckFlag()));

                cell1= getCell(row1, 2);
                cell1.setCellValue(ad.getAssetsName());

                cell1= getCell(row1, 3);
                cell1.setCellValue(ad.getAssetsSn());

                cell1= getCell(row1, 4);
                cell1.setCellValue(dictDataService.selectDictLabel("assets_status", ad.getAssetsStatus()));

                cell1= getCell(row1, 5);
                cell1.setCellValue(dictDataService.selectDictLabel("assets_type", ad.getAssetsType()));

                cell1= getCell(row1, 6);
                cell1.setCellValue(ad.getAssetsModel());

                cell1= getCell(row1, 7);
                cell1.setCellValue(ad.getDeptName());

                cell1= getCell(row1, 8);
                cell1.setCellValue(ad.getUserName());

                cell1= getCell(row1, 9);
                cell1.setCellValue(ad.getCheckUserName());

                cell1= getCell(row1, 10);
                if(ad.getCheckTime()!=null && !"".equals(ad.getCheckTime())){
                    cell1.setCellValue(DateUtils.dateTime(ad.getCheckTime()));
                }else{
                    cell1.setCellValue("");
                }

            }
        }
    }


    /**
     * base64字符串，分隔图片类型和base64串码
     * @param base64
     * @return [0]-type; [1]-base64Str
     */
    public static String [] base64SplitTypeAndStr(String base64){
        String [] retArr = {"", ""};
        if(StringUtils.isNotBlank(base64)){
            //先取出前缀
            String typeStr = base64.split(",")[0];
            //去掉前缀后的串码
            retArr[1] = base64.replaceFirst(typeStr+",", "");
            //取出图片类型
            retArr[0] = typeStr.replace("data:image/", "").replace(";base64", "");
        }
        return retArr;
    }

    /**
     * base64 编码转换为 BufferedImage
     * @param base64
     * @return
     */
    public static BufferedImage base64ToBufferedImage(String base64) {
        try {
            byte[] bytes1 = DatatypeConverter.parseBase64Binary(base64);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            return ImageIO.read(bais);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    public String getAbsoluteFile(String filename)
    {
        String downloadPath = ZyjConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    /**
     * 编码文件名
     */
    public String encodingFilename(String filename)
    {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
        return filename;
    }


    private HSSFCellStyle exportExcelSetCellStyle(HSSFWorkbook wb){
        HSSFCellStyle style = wb.createCellStyle();
        /*背景色填充*/
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        /*设置字体*/
        HSSFFont font = wb.createFont();
        font.setFontName("仿宋_GB2312");
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        /*居中对齐*/
        style.setAlignment(HorizontalAlignment.CENTER);
        return style;
    }
}
